import os
import sys
import psutil

def kill_process_on_port(port):
    """终止占用指定端口的进程"""
    for proc in psutil.process_iter(['pid', 'name', 'connections']):
        try:
            for conn in proc.info['connections'] or []:
                if conn.laddr.port == port:
                    print(f"找到进程 PID {proc.info['pid']} ({proc.info['name']}) 占用端口 {port}")
                    proc.terminate()
                    print(f"已终止进程 {proc.info['pid']}")
                    return True
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            pass
    return False

if __name__ == "__main__":
    port = int(sys.argv[1]) if len(sys.argv) > 1 else 5001
    if kill_process_on_port(port):
        print(f"成功释放端口 {port}")
    else:
        print(f"没有找到占用端口 {port} 的进程")